var url = "https://detail.tmall.com/item.htm?spm=a220m.1000858.1000725.1.2a7d1f675x6eyH&id=541017907539&areaId=340100&user_id=2457021025&cat_id=2&is_b=1&rn=fa715ecb39805b48033d50fa489f2ddf&sku_properties=1627207:90554;6863381:4104438";
var page = require('webpage').create();
var retJsonpObj = null;

var setMdskip = function(obj){
	retJsonpObj = obj;
};

page.captureContent = [ /.*/ ];
page.settings.loadImages = false;

page.onResourceReceived = function(response) {
	if(response.url.indexOf('initItemDetail')>-1){
		//这里回调setMdskip方法
		eval(response.body);
	}
};
page.onError = function(msg,trace){
	var msgStack = ['ERROR: ' + msg];
	if (trace && trace.length) {
		msgStack.push('TRACE:');
		trace.forEach(function(t) {
			msgStack.push(' -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function + '")' : ''));
		});
	}
	// uncomment to log into the console 
	// console.error(msgStack.join('\n'));
	//phantom.exit();
};
page.open(url,function(status){
	var analyzeObj = page.evaluate(function(){
		var scriptObj = null;
		var TShop = {
			poc : function(str){
				//console.log(str);
			},

			setConfig : function(obj){
				//console.log("setConfig run");
			},

			Setup : function(obj){
				//console.log("setConfig run");
				scriptObj = obj;
			}
		};

		//页面中dom提取的信息=========================================================
		var objArr = [];
		var dls = document.querySelectorAll("div.tb-sku > dl.tm-sale-prop");  //查找所有dl
		for(var a=0;a<dls.length;a++){
			var dlElement = dls[a];
			var dt = dlElement.querySelector("dt"); //查找属性类别
			
			var dataValues = dlElement.querySelectorAll("dd > ul > li");  //所有data-value
			var dataValueArr = [];
			for(var b=0;b<dataValues.length;b++){
			var dataValue = dataValues[b].getAttribute("data-value");
			var title = dataValues[b].querySelector("a > span").textContent;
			dataValueArr[b] = {key:dataValue,value:title};
			}
			objArr[a] = {attrTypes:dt.textContent,dataValues:dataValueArr};
		}

		var default_img = document.querySelector("#J_ImgBooth").src;	//页面中默认图片地址

		//页面中script中提取的信息=======================================================
		var jsList = document.querySelectorAll("script");	//所有js
		for(var i=0;i<jsList.length;i++){
			var content = jsList[i].textContent;
			if(content.indexOf("TShop.setConfig")>-1 && content.indexOf("detail")>-1){
				eval(content);
			}else{
				continue;
			}
		}
		var obj = {pageScriptObj:scriptObj,detailAttr:objArr,defaultImg:default_img}
		return obj;
	});
	var retObj = {};
	retObj.platform = 'tmall';
	retObj.jsonpObj = retJsonpObj;
	retObj.analyzeObj = analyzeObj;
	console.log(JSON.stringify(retObj));
	phantom.exit();
});


